using System;
using System.Drawing;
using System.Drawing.Imaging;
using Lime;

namespace Clandestine.Graphics
{
	public class BitmapTexture : Texture
	{
		private Size size;
		public override Size Size { get { return size; } }
		
		internal BitmapTexture(Graphics graphics, string identifier, Bitmap bmp, bool treatAsIndexed, bool linearInterpolaition, bool keepAlive = false)
			: base (graphics, identifier, linearInterpolaition, keepAlive)
		{
			// Handle chroma-keying of the bitmap, if necessary
			bmp = BitmapHelper.ChromaKeyIfNecessary(bmp, treatAsIndexed);
			
			// Create our texture & upload bitmap data
			createNewGlTexture();
			uploadBitmap(bmp);
			
			// Remember size of the bitmap
			this.size = bmp.Size;
		}
		
		private void uploadBitmap(Bitmap bitmap)
        {
        	base.Graphics.BlockRendering();
			base.Graphics.WindowInternal.MakeContextCurrent();
			
            GL.Enable(EnableCap.Texture2D);

			GL.BindTexture(TextureTarget.Texture2D, TexturePointer);
        
        	lock (bitmap)
            {
            	Bitmap bmpTex = bitmap;
               	
                BitmapData bd = bmpTex.LockBits(new Rectangle(0, 0, bmpTex.Width, bmpTex.Height),
                    ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
       			             
                // Actually upload the data.
				GL.TexImage2D(TextureTarget.Texture2D, 0, (int)PixelInternalFormat.Rgba8, bd.Width, bd.Height, 0, (Lime.PixelFormat)GLEnum.Bgra, PixelType.UnsignedByte, bd.Scan0); // TODO: PixelFormat enum missing an entry! :x

                bmpTex.UnlockBits(bd);
            }
            
            GL.Disable(EnableCap.Texture2D);

			base.Graphics.WindowInternal.ReleaseContext();
			base.Graphics.UnblockRendering();
        }
	}
}

